import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import { fetchUserImage, removeImage, fetchPatient, changePage, mPacs} from '../../store/actions';
import {message,Card, Col, Row,Button,TimeLine,Tag,Modal} from 'antd';

require('../../../css/label-list.css');

class _ImageDetail extends React.Component{
    constructor(props){
        super(props);
        this.state= {
            image:{},
            patient:{},
            modal:{
                title:'',
                text:'',
                visible:false
            }
        };
        this.goToEditPatient = this.goToEditPatient.bind(this);
        this.viewImage = this.viewImage.bind(this);
        this.deleteImage = this.deleteImage.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.handleOk = this.handleOk.bind(this);
        this.imageOperate = this.imageOperate.bind(this);
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    goToEditPatient(){
        const pid = this.state.patient.id;
        this.context.router.push(`/patient-edit/${pid}`)
    }
    handleOk(){
        const _this = this,
        studyId = _this.state.image.id;
        _this.setState({
            modal: {
                confirmLoading: true,
                visible:true,
                text:'您确认要删除这个影像吗？',
                title:'删除影像'
            }
        },function(){
            _this.props.dispatch(removeImage(studyId,function(){
                message.success('删除影像成功',1,function(){
                    _this.setState({
                        modal: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:''
                        }
                    },function(){
                        _this.context.router.push('/images')
                    })
                })
            },function(e){
                message.error('删除影像失败: 功能暂未开放',2,function(){
                    _this.setState({
                        modal: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:''
                        }
                    })
                })

            }))
        });
    }
    handleCancel(){
        this.setState({
            modal:{
                visible:false
            }
        })
    }
    deleteImage(){
        this.setState({
            modal:{
                visible:true,
                text:'您确认要删除这个影像吗？',
                title:'删除影像'
            }
        });
    }
    share(){}
    viewImage(){
        if(!!this.state.image.study_instance_uid){
            this.props.dispatch(mPacs(this.state.image.study_instance_uid,function(url){
                window.open(
                    url,
                    'viewer',
                    'location=no,toolbar=no,alwaysRaised=yes,screenX=0,screenY=0'
                );
            }))
        }else{
            message.warning('影像还没有准备好')
        }
    }
    componentWillMount(){
        this.props.dispatch(changePage('image-detail'));
        const _this= this,
            _id = _this.props.params.id;
        try{
            _this.props.dispatch(fetchUserImage(_id,function(res){
                const image = res.content,
                        pid = image.pid;
                _this.props.dispatch(fetchPatient(pid,function(res){
                    const newState = {
                        image,
                        patient: res.content
                    };
                    if(newState.patient.address){
                        let _address = newState.patient.address.split('$');
                        if(_address.length>=3)
                            newState.patient.all_address = _address[1] + ' ' + _address[2];
                        else
                            newState.patient.all_address = _address[0]
                    }
                    _this.setState({...newState});
                }));
            },function(res){
                const _msg = res.head.msg,
                    cause = /accessToken/.test(_msg);
                if(cause){
                    message.error('您的账户已过期，请重新登录',1);
                    this.context.router.push('/login');
                }else{
                    message.error('获取影像失败',1,function(){
                        _this.context.router.push('/images')
                    })
                }
            }));
        }catch(e){console.error(e)}
    }
    imageOperate(status){
        switch (status){
            case -1:
            case 0:
                return (
                    <div>
                        <Button type="ghost" icon="delete" size="small" onClick={this.deleteImage}>删除</Button>
                    </div>
                );
            case -2:
            case 1:
            case 2:
                return (
                    <div>
                        <Button type="primary" icon="eye" size="large" onClick={this.viewImage}>查看影像</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="ghost" icon="delete" size="small" onClick={this.deleteImage}>删除</Button>
                    </div>
                );
            /*
            case 2:
            return (
                    <div>
                        <Button type="primary" icon="eye" size="large" onClick={this.viewImage}>查看影像</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        {<Button type="ghost" disabled icon="share-alt" size="large" onClick={this.share}>分享</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;}
                        <Button type="ghost" icon="delete" size="small" onClick={this.deleteImage}>删除</Button>
                    </div>
                );*/
            default:
                return ''

        }
    }
    render(){
        return(
            <div style={{ background: '', padding: '10px' }}>
                {/**
                * image.statue:
                * -2 => 驳回（审核不通过）
                * -1 => 到入出错
                * 0 => 未导入
                * 1 => 已导入，未审核
                * 2 => 已审核
                * */}
                <Row type="" justify="space-around" align="top">
                    <Col xs={{span:11}}
                         sm={{span:11}}
                         md={{span:10}}
                         lg={{span:10}}
                    >
                        <Card title={`影像信息`} bordered={false}>
                            <ul className="label-list">
                                <li><label>来源</label>{this.state.image.origin || `个人上传`} </li>
                                <li><label>设备类型</label>{this.state.image.modality || `--`} </li>
                                <li><label>检查部位</label>{this.state.image.bodypart || `--`} </li>
                                <li><label>检查项目</label>{this.state.image.check_item_name || `--`} </li>
                                <li><label>检查费用</label>{this.state.image.cost || `--`} </li>
                                <li><label>检查日期</label>{this.state.image.studydate || `--`} </li>
                                <li><label>检查时年龄</label>{this.state.image.patientage || `--`} </li>
                                <li><label>影像号</label>{this.state.image.study_instance_uid || `--`} </li>
                                <li><label>检查号</label>{this.state.image.check_code || `--`} </li>
                                <li><label>检查机构</label>{this.state.image.institution || `--`} </li>
                                <li><label>设备品牌</label>{this.state.image.modality_brand || `--`} </li>
                                <li><label>设备型号</label>{this.state.image.modality_type || `--`} </li>
                                <li><label>导入时间</label>{this.state.image.importdate || '--'}</li>
                                {this.state.image.status == -2?<li><label>拒绝理由</label>{this.state.image.memo}</li>:''}
                                {this.state.image.status == -1?<li><label>失败原因</label>{this.state.image.memo}</li>:''}

                            </ul>
                            {this.imageOperate(this.state.image.status)}
                        </Card>
                        <Card title={`病症信息`} bordered={false}>
                            <ul className="label-list">
                                <li><label>临床诊断</label>{this.state.image.diagnosis || `--`} </li>
                                <li><label>症状描述</label>{this.state.image.symptom || `--`} </li>
                            </ul>
                        </Card>
                    </Col>
                    <Col xs={{span:11,offset:1}}
                         sm={{span:11,offset:1}}
                         md={{span:10,offset:1}}
                         lg={{span:10,offset:1}}
                    >
                        <Card title={`基本信息`} bordered={false}>
                            <ul className="label-list">
                                <li><label>姓名</label>{this.state.patient.name || `佚名`} </li>
                                <li><label>性别</label>{`${this.state.patient.gender}`==`M`?`男`:`女`} </li>
                                <li><label>生日</label>{this.state.patient.birthday || `--`} </li>
                                <li><label>年龄</label>{this.state.patient.age} </li>
                                <li><label>身份证</label>{this.state.patient.idcard || `--`} </li>
                                <li><label>社保号</label>{this.state.patient.social_insurance || `--`} </li>
                                <li><label>联系方式</label>{this.state.patient.mobile || `--`} </li>
                                <li><label>地址</label>{this.state.patient.all_address || `--`} </li>
                                <li><label>关系</label>{this.state.patient.relationship ||`--`} </li>
                                <li><label>过往病史</label>{this.state.patient.medical_history || `--`} </li>
                                <li><label>状态</label>{this.state.patient.status == 0? <Tag color="">已删除</Tag>:<Tag color="green">正常</Tag>}</li>
                            </ul>
                        </Card>
                        {/*<Card title={`影像单据`} bordered={false}>
                            <ul className="label-list">
                                <li></li>
                                <li></li>
                            </ul>
                        </Card>*/}
                    </Col>
                </Row>
                <Modal title={this.state.modal.title}
                       visible={this.state.modal.visible}
                       onOk={this.handleOk}
                       confirmLoading={this.state.modal.confirmLoading}
                       onCancel={this.handleCancel}
                >
                    <p>{this.state.modal.text}</p>
                </Modal>
            </div>
        )
    }
}

/**
 * @#$注意：
 * 初步加载时fetch了数据，
 * 后面还使用connect关联store中的数据，
 * 这是重复的，以后根据数据缓存策略再作调整
 * */

const ImageDetail = connect((state)=>{
    const {user} = state.rootReducer;
    const {patients} = state.rootReducer.patients.items;
    const {images} = state.rootReducer.images.items;
    return {user,patients,images}
})(_ImageDetail);
export default ImageDetail;